﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MebApp.Launcher.Helpers
{
    public class ZipHelper
    {
        public static void UnZip(string zipFile, string destination)
        {
            ZipArchive archive = new ZipArchive(File.OpenRead(zipFile));
            foreach (ZipArchiveEntry entry in archive.Entries)
            {
                using (var stream = entry.Open())
                {
                    var itemPath = Path.Combine(destination, entry.FullName);
                    var itemDir = Path.GetDirectoryName(itemPath);
                    if (!Directory.Exists(itemDir))
                        Directory.CreateDirectory(itemDir);
                    using (var fs = File.Create(itemPath))
                    {
                        stream.CopyTo(fs);
                    }
                }
            }
        }
        public static void UnZip(Stream zipFileStream, string destination)
        {
            ZipArchive archive = new ZipArchive(zipFileStream);
            foreach (ZipArchiveEntry entry in archive.Entries)
            {
                using (var stream = entry.Open())
                {
                    var itemPath = Path.Combine(destination, entry.FullName);
                    var itemDir = Path.GetDirectoryName(itemPath);
                    if (!Directory.Exists(itemDir))
                        Directory.CreateDirectory(itemDir);
                    using (var fs = File.Create(itemPath))
                    {
                        stream.CopyTo(fs);
                    }
                }
            }
        }

        public static void ZipFiles(string dir, string[] files, string outputFile)
        {
            var tempFile = Path.GetTempFileName();
            using (ZipArchive archive = new ZipArchive(File.Open(tempFile, FileMode.OpenOrCreate)))
            {
                foreach (var file in files)
                {
                    var relativePath = file.Replace(dir, "").TrimStart('/', '\\');
                    var entry = archive.CreateEntry(relativePath);
                    using (var stream = entry.Open())
                    {
                        using (var fs = File.OpenRead(file)) { fs.CopyTo(stream); }
                    }
                }
            }
            if (File.Exists(outputFile))
            {
                File.Copy(tempFile, outputFile, true);
                File.Delete(tempFile);
            }
            else
            {
                File.Move(tempFile, outputFile);
            }
        }
    }
}
